package cn.ctodb.wxmp.service;

import cn.ctodb.wxmp.config.MpConstants;
import cn.ctodb.wxmp.domain.UserInfo;
import cn.ctodb.wxmp.repository.MpRepository;
import cn.ctodb.wxmp.repository.UserInfoRepository;
import cn.ctodb.wxmp.repository.search.UserInfoSearchRepository;
import cn.ctodb.wxmp.service.dto.UserInfoDTO;
import cn.ctodb.wxmp.service.mapper.UserInfoMapper;
import cn.ctodb.wxmp.util.HttpUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.inject.Inject;

import static org.elasticsearch.index.query.QueryBuilders.queryStringQuery;

/**
 * Service Implementation for managing UserInfo.
 */
@Service
@Transactional
public class UserInfoService {

    private final Logger log = LoggerFactory.getLogger(UserInfoService.class);

    @Inject
    private UserInfoRepository userInfoRepository;

    @Inject
    private UserInfoMapper userInfoMapper;

    @Inject
    private UserInfoSearchRepository userInfoSearchRepository;

    @Inject
    private MpRepository mpRepository;

    @Inject
    private TokenService tokenService;


    /**
     * Save a userInfo.
     *
     * @param userInfoDTO the entity to save
     * @return the persisted entity
     */
    public UserInfoDTO save(UserInfoDTO userInfoDTO) {
        log.debug("Request to save UserInfo : {}", userInfoDTO);
        UserInfo userInfo = userInfoMapper.userInfoDTOToUserInfo(userInfoDTO);
        userInfo = userInfoRepository.save(userInfo);
        UserInfoDTO result = userInfoMapper.userInfoToUserInfoDTO(userInfo);
        userInfoSearchRepository.save(userInfo);
        return result;
    }

    /**
     * Get all the userInfos.
     *
     * @param pageable the pagination information
     * @return the list of entities
     */
    @Transactional(readOnly = true)
    public Page<UserInfoDTO> findAll(Pageable pageable) {
        log.debug("Request to get all UserInfos");
        Page<UserInfo> result = userInfoRepository.findAll(pageable);
        return result.map(userInfo -> userInfoMapper.userInfoToUserInfoDTO(userInfo));
    }

    /**
     * Get one userInfo by id.
     *
     * @param id the id of the entity
     * @return the entity
     */
    @Transactional(readOnly = true)
    public UserInfoDTO findOne(Long id) {
        log.debug("Request to get UserInfo : {}", id);
        UserInfo userInfo = userInfoRepository.findOne(id);
        UserInfoDTO userInfoDTO = userInfoMapper.userInfoToUserInfoDTO(userInfo);
        return userInfoDTO;
    }

    /**
     * Delete the  userInfo by id.
     *
     * @param id the id of the entity
     */
    public void delete(Long id) {
        log.debug("Request to delete UserInfo : {}", id);
        userInfoRepository.delete(id);
        userInfoSearchRepository.delete(id);
    }

    /**
     * Search for the userInfo corresponding to the query.
     *
     * @param query the query of the search
     * @return the list of entities
     */
    @Transactional(readOnly = true)
    public Page<UserInfoDTO> search(String query, Pageable pageable) {
        log.debug("Request to search for a page of UserInfos for query {}", query);
        Page<UserInfo> result = userInfoSearchRepository.search(queryStringQuery(query), pageable);
        return result.map(userInfo -> userInfoMapper.userInfoToUserInfoDTO(userInfo));
    }

    public void init(Long id) {
        init(id, null);
    }

    private void init(Long id, String openid) {
        String accessToken = tokenService.getAccessToken(id).getAccessToken();
        String requestUrl = MpConstants.USER_GET.replace("ACCESS_TOKEN", accessToken).replace("NEXT_OPENID", openid == null ? "" : openid);
        String re = HttpUtils.get(requestUrl);
        log.debug(re);
        try {
            JSONObject rej = new JSONObject(re);
            JSONArray ja = rej.getJSONObject("data").getJSONArray("openid");
            for (int i = 0; i < ja.length(); i++) {
                openid = ja.getString(i);
                log.debug(openid);
                UserInfo ui = userInfoRepository.findOneByOpenid(openid);
                if (ui == null) {
                    ui = new UserInfo();
                    ui.setOpenid(openid);
                    ui.setMp(mpRepository.getOne(id));
                    userInfoRepository.save(ui);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
